package com.banshuibao.bsb_android.activity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.HistoryAdapter;
import com.banshuibao.bsb_android.database.DataBaseHelper;
import com.banshuibao.bsb_android.view.EditText_Clear;

import java.util.ArrayList;
import java.util.List;

public class DataQuery1Activity extends BaseActivity implements TextWatcher, View.OnClickListener {

    private String tag;
    private EditText_Clear editText_clear;
    private RecyclerView recyclerView;
    private LinearLayout history;
    private TextView menu;
    private DataBaseHelper baseHelper;
    private SQLiteDatabase db;
    private String intoSql="insert into history values(null,?,?)";
    private String q = "select title from history where title =?";
    private List<String> list = new ArrayList<>();
    private HistoryAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_query);
        tag = getIntent().getStringExtra("tag");
        // 得到对象
        baseHelper = new DataBaseHelper(this, null);
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        queryData();
        if(list!=null&&list.size()>0){
            history.setVisibility(View.VISIBLE);
        }else{
            history.setVisibility(View.GONE);
        }
    }

    public void initView() {
        editText_clear = findViewById(R.id.et_search);
        recyclerView = findViewById(R.id.recyclerView);
        history = findViewById(R.id.history);
        menu = findViewById(R.id.menu);
    }

    public void initData() {
        switch (tag) {
            case "repository":
                editText_clear.setHint("搜索知识");
                break;
            case "case":
                editText_clear.setHint("搜索案例");
                break;
        }

        editText_clear.addTextChangedListener(this);
        menu.setOnClickListener(this);
        history.setOnClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this,2));
        adapter = new HistoryAdapter(this);
        recyclerView.setAdapter(adapter);
    }

    public void queryData(){
        db = baseHelper.getWritableDatabase();
        Cursor cursor = db.query("history", null, null, null, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            // 得到列名对就索引号
            int index_name = cursor.getColumnIndex("title");
			/*
			 * 遍历cursor得到值(新方法) 参数一：cursor值中第一个 参数二：判断cursor是否为最后一个
			 * 参数三：判断cursor是为还有下一个值
			 */
            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
                    .moveToNext()) {
                // 根据索引号得到对应值
                String name = cursor.getString(index_name);
                list.add(name);
            }
        }
        cursor.close();
        db.close();
        adapter.setData(list);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.length()>0){
            menu.setText("搜索");
        }else{
            menu.setText("取消");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.history:

                break;
            case R.id.menu:
                String s = menu.getText().toString().trim();
                String content = editText_clear.getText().toString().trim();
                if(TextUtils.equals(s,"搜索")){
                    long time=System.currentTimeMillis();
                    if(!hasData(content)){
                        insertData(content,time);
                    }
                    adapter.notifyDataSetChanged();
                }else{
                    editText_clear.setText("");
                    finish();
                }
                break;
        }

    }

    /**
     * 检查数据库中是否已经有该搜索记录
     */
    private boolean hasData(String tempName) {
        // 从数据库中Record表里找到name=tempName的id
        Cursor cursor = baseHelper.getReadableDatabase().rawQuery(q, new String[]{tempName});
        //  判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 插入数据到数据库，即写入搜索字段到历史搜索记录
     */
    private void insertData(String tempName,long time) {
        db = baseHelper.getWritableDatabase();
        db.execSQL(intoSql,new Object[]{tempName,time});
        db.close();
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = editText_clear;
            if (v != null && isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1] - 20;
            int bottom = top + v.getHeight() + 20;
            int right = left + getWindow().getDecorView().getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


}
